package com.free4inno.knowledgems.service;

import com.free4inno.knowledgems.dao.SystemManageDAO;
import com.free4inno.knowledgems.dao.UserDAO;
import com.free4inno.knowledgems.domain.SystemManage;
import com.free4inno.knowledgems.domain.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

@Slf4j
@Service
public class AppKeyService {

    @Autowired
    private UserDAO userDao;

    @Autowired
    private SystemManageDAO systemManageDao;

    public Map<String, Object> checkAppKey(String appKey) {
        log.info(this.getClass().getName() + "----in----" + "校验appKey合法性（checkAppKey）" + "----");
        log.info(this.getClass().getName() + "----" + "appKey:" + appKey);
        Map<String, Object> res = new HashMap<>();
        if (!appKey.isEmpty()) {
            // 1. 检查是否为某一用户的appKey
            Optional<User> user = userDao.findAllByAppKey(appKey);
            if (user.isPresent()) {
                res.put("result", true);
                res.put("identity", "user");
                res.put("user", user.get());
                log.info(this.getClass().getName() + "----out----" + "校验通过，用户appKey" + "----");
                return res;
            }
            // 2. 检查是否为公开的appKey
            SystemManage systemManage = systemManageDao.findAllByVariable("appKey_public").orElse(new SystemManage());
            if (systemManage.getValue().equals(appKey)) {
                res.put("result", true);
                res.put("identity", "public");
                res.put("user", null);
                log.info(this.getClass().getName() + "----out----" + "校验通过，公共appKey" + "----");
                return res;
            }
        }
        // 3. 不合法的appKey
        res.put("result", false);
        res.put("identity", "illegal");
        res.put("user", null);
        log.info(this.getClass().getName() + "----out----" + "校验失败，非法appKey" + "----");
        return res;
    }

}
